package com.lx.wxdemo.controller;

import com.lx.wxdemo.entity.Order;
import com.lx.wxdemo.service.OrderService;
import com.lx.wxdemo.utils.OrderUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @Description 订单controller, 微信小程序点击支付会将所购商品信息发送到后台, 后台根据这些信息生成订单
 * 包括:  订单号,商品详情，价格，重量，总价，创建时间，对应的openid，手机号等。。。
 * @Author lx
 * @Date 2021/1/6 9:23
 **/
@Api("订单管理")
@RestController
public class OrderController {

    @Autowired
    private OrderService orderService;

    @ApiOperation("生成订单接口测试")
    @RequestMapping("/createOrder")
    public String createOrder(HttpServletRequest request, HttpServletRequest httpResponse) {
        //订单号
        String orderId = OrderUtils.createOrderId();
        //商品名称
        String product = request.getParameter("product");
        //商品重量
        String weight = request.getParameter("weight");
        //商品总价
        String total = request.getParameter("total");
        //买家openid
        String b_openid = request.getParameter("b_openid");
        //卖家openid
        String s_openid = request.getParameter("s_openid");
        //订单生成时间
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(date);
        //订单支付状态
        String pay_status = "1";//生成订单时默认是未支付状态

        Order order = new Order();
        order.setOrderId(orderId);
        order.setProduct(product);
        order.setWeight(weight);
        order.setTotal(total);
        order.setB_openid(b_openid);
        order.setS_openid(s_openid);
        order.setCreatetime(date);
        order.setPay_status(pay_status);
        System.out.println(order);

        //将订单存入数据库中
        //TODO 此处应该返回一个boolean值或者一个数值,用于判断订单是否保存成功
        //对于普通的 INSERT 插入，如果想要保证不插入重复记录我们只有对某个字段创建唯一约束实现；
        // 不创建唯一约束，仅通过 INSERT INTO 一条语句实现的方案呢？
        /**
         INSERT INTO a (order_id, operator, oper_date, memo)
         SELECT '3', 'onion3', '2017-11-28', '测试3'
         from DUAL
         where not exists(select order_id from a where operator='onion3' and memo = '测试3');
         */
        orderService.save(order);

        //TODO 最终返回值应该是返回一个可选择的支付列表(银联/微信/支付宝 支付)
        //此处做测试,先返回字符串
        return "你的订单生成成功";

    }

}
